package com.gzc.just.play.last.war.robotclient;

import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import com.alibaba.nacos.api.naming.pojo.Instance;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.serviceregistry.Registration;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * Nacos服务注册发现类
 * 用于监控服务器状态并更新配置
 */
@Component
public class NacosServiceWatcher {
    private static final Logger log = LoggerFactory.getLogger(NacosServiceWatcher.class);
    
    // 服务发现客户端
    @Autowired(required = false)
    private DiscoveryClient discoveryClient;
    
    // 服务实例缓存
    private final Map<String, List<Instance>> serviceInstances = new ConcurrentHashMap<>();
    
    // 服务注册信息
    private Registration loginServerRegistration;
    private Registration gateServerRegistration;
    
    // 定时任务执行器
    private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
    
    // 是否已启动
    private volatile boolean started = false;
    
    /**
     * 启动服务监听
     */
    public void start() {
        if (started) {
            log.warn("NacosServiceWatcher is already started");
            return;
        }
        
        started = true;
        log.info("Starting Nacos service watcher");
        
        // 启动定时检查任务
        scheduler.scheduleAtFixedRate(this::checkServices, 10, 10, TimeUnit.SECONDS);
        
        log.info("Nacos service watcher started");
    }
    
    /**
     * 停止服务监听
     */
    public void stop() {
        if (!started) {
            return;
        }
        
        started = false;
        log.info("Stopping Nacos service watcher");
        
        // 停止定时任务
        scheduler.shutdown();
        
        // 注销服务注册
        unregisterServices();
        
        log.info("Nacos service watcher stopped");
    }
    
    /**
     * 获取登录服务器地址
     */
    public String getLoginServerHost() {
        List<Instance> instances = serviceInstances.get("login-server");
        
        if (instances != null && !instances.isEmpty()) {
            return instances.get(0).getIp();
        }
        
        // 返回默认地址
        return "127.0.0.1";
    }
    
    /**
     * 获取登录服务器端口
     */
    public int getLoginServerPort() {
        List<Instance> instances = serviceInstances.get("login-server");
        
        if (instances != null && !instances.isEmpty()) {
            return instances.get(0).getPort();
        }
        
        // 返回默认端口
        return 30001;
    }
    
    /**
     * 获取网关服务器地址
     */
    public String getGateServerHost() {
        List<Instance> instances = serviceInstances.get("gate-server");
        
        if (instances != null && !instances.isEmpty()) {
            return instances.get(0).getIp();
        }
        
        // 返回默认地址
        return "127.0.0.1";
    }
    
    /**
     * 获取网关服务器端口
     */
    public int getGateServerPort() {
        List<Instance> instances = serviceInstances.get("gate-server");
        
        if (instances != null && !instances.isEmpty()) {
            return instances.get(0).getPort();
        }
        
        // 返回默认端口
        return 40001;
    }
    
    /**
     * 检查服务状态
     */
    private void checkServices() {
        if (discoveryClient == null) {
            log.debug("DiscoveryClient not available, skipping service check");
            return;
        }
        
        try {
            // 获取登录服务器实例
            List<ServiceInstance> loginServices = discoveryClient.getInstances("login-server");
            if (loginServices != null && !loginServices.isEmpty()) {
                serviceInstances.put("login-server", convertToNacosInstances(loginServices));
                log.debug("Found {} login server instances", loginServices.size());
            }
            
            // 获取网关服务器实例
            List<ServiceInstance> gateServices = discoveryClient.getInstances("gate-server");
            if (gateServices != null && !gateServices.isEmpty()) {
                serviceInstances.put("gate-server", convertToNacosInstances(gateServices));
                log.debug("Found {} gate server instances", gateServices.size());
            }
            
        } catch (Exception e) {
            log.error("Error checking services", e);
        }
    }
    
    /**
     * 将Spring Cloud ServiceInstance转换为Nacos Instance
     */
    private List<Instance> convertToNacosInstances(List<ServiceInstance> serviceInstances) {
        Map<String, Instance> instances = new HashMap<>();
        
        for (ServiceInstance serviceInstance : serviceInstances) {
            Instance instance = new Instance();
            instance.setInstanceId(serviceInstance.getInstanceId());
            instance.setIp(serviceInstance.getHost());
            instance.setPort(serviceInstance.getPort());
            Object weightObj = serviceInstance.getMetadata().get("weight");
            double weight = weightObj != null ? Double.parseDouble(weightObj.toString()) : 1.0;
            instance.setWeight(weight);
            instance.setEnabled(true);
            instance.setHealthy(true);
            instance.setEphemeral(true);
            
            // 添加元数据
            Map<String, String> metadata = new HashMap<>();
            metadata.putAll(serviceInstance.getMetadata());
            metadata.put("region", "default");
            metadata.put("zone", "default");
            instance.setMetadata(metadata);
            
            instances.put(serviceInstance.getInstanceId(), instance);
        }
        
        return List.copyOf(instances.values());
    }
    
    /**
     * 注册服务
     */
    public void registerService(String serviceName, String host, int port) {
        try {
            Map<String, String> metadata = new HashMap<>();
            metadata.put("version", "1.0.0");
            metadata.put("type", "robot-client");
            
            // Service registration is handled by Spring Cloud Nacos automatically
            log.info("Service registration handled by Spring Cloud: {} -> {}:{}", serviceName, host, port);
            
        } catch (Exception e) {
            log.error("Failed to register service: {}", serviceName, e);
        }
    }
    
    /**
     * 注销服务
     */
    private void unregisterServices() {
        try {
            // Service deregistration is handled by Spring Cloud Nacos automatically
            if (loginServerRegistration != null) {
                loginServerRegistration = null;
                log.info("Deregistered login-server service");
            }
            
            if (gateServerRegistration != null) {
                gateServerRegistration = null;
                log.info("Deregistered gate-server service");
            }
        } catch (Exception e) {
            log.error("Failed to unregister services", e);
        }
    }
}